/*
 *  cocoa/windowImp.cpp
 *  mini
 *
 *  Created by jin on 1/1/11.
 *  Copyright 2011 cs. All rights reserved.
 *
 */
#include "cocoa/windowImp.h"

#include "window.h"
#include "cocoa/graphic2D.h"
#include "mouseEvent.h"

#import <Cocoa/Cocoa.h>


@interface CocoaWindow : NSWindow
{
}
@end


@implementation CocoaWindow
@end

@interface CocoaView : NSView
{
    Window* owner;
}
- (void) NSEventToMouseEvent : (NSEvent *)theEvent outEvent:(MouseEvent&) mouseEvent;

- (void) setOwner : (Window*) owner;
@end

@implementation CocoaView
- (void) drawRect : (NSRect) rect
{
    // Drawing code here.
    CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
    CocoaGraphic2D cgc(cg);
    owner->OnPaint(cgc);
}

- (BOOL) isFlipped
{
	return YES;
}

- (void) setOwner : (Window*) owner_
{
    owner = owner_;
}

- (void) NSEventToMouseEvent : (NSEvent *)theEvent outEvent : (MouseEvent&) mouseEvent
{
	NSPoint event_location = [theEvent locationInWindow];
	event_location = [self convertPoint:event_location fromView:nil];
	
	mouseEvent.x = event_location.x;
	mouseEvent.y = event_location.y;
}

- (void)mouseDown : (NSEvent *)theEvent
{
	MouseEvent e;
	[self NSEventToMouseEvent: theEvent outEvent: e];

	owner->OnMouseDown(e);
}

- (void)mouseUp : (NSEvent *)theEvent
{
	MouseEvent e;
	[self NSEventToMouseEvent: theEvent outEvent: e];
	
	owner->OnMouseUp(e);
}

- (void)mouseDragged : (NSEvent *)theEvent
{
	MouseEvent e;
	[self NSEventToMouseEvent: theEvent outEvent: e];
	
	owner->OnMouseMove(e);
}

- (void)dealloc
{
	delete owner;
	[super dealloc];
}

@end


CocoaWindowImp::CocoaWindowImp(Window* owner_) : WindowImpBase(owner_)
{
    NSRect rc = NSMakeRect(0, 0, 800, 600);

    NSUInteger uiStyle = NSTitledWindowMask | NSResizableWindowMask | NSClosableWindowMask;

    NSBackingStoreType backingStoreStyle = NSBackingStoreBuffered;

    pImp = [[CocoaWindow alloc] initWithContentRect : rc styleMask : uiStyle backing : backingStoreStyle defer : NO];

    // TODO : set to transprent
    //[pImp setOpaque:YES];
    //[pImp setAlphaValue:0.9999];

    // TODO : set as main window
    //[pImp makeMainWindow];

    pView = [[CocoaView alloc] init];
    [pView setOwner : owner];
    [pImp setContentView : pView];
	[pView release];
}

CocoaWindowImp::~CocoaWindowImp()
{
}

void* CocoaWindowImp::GetHandle()
{
	return pImp;
}

void CocoaWindowImp::Show(bool show)
{
	if (pImp)
		[pImp makeKeyAndOrderFront : pImp];
}
